﻿using Business;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

namespace BVVD_Website.ql_hoc_tap
{
    public partial class frmLopMonhoc : System.Web.UI.Page
    {
        public static string mfrm = "MNU024";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                BVVDDataContext db = new BVVDDataContext();
                if (Session["user"] != null)
                {
                    LST_NSD user = Session["user"] as LST_NSD;

                    V_PHANQUYEN pq = (from p in db.V_PHANQUYENs
                                      where p.MAMN.Equals(mfrm) && p.MANSD.Equals(user.MANSD)
                                      select p).SingleOrDefault();
                    if (pq != null)
                    {
                        grvLopMonhoc.MasterTableView.CommandItemSettings.ShowAddNewRecordButton = pq.ADD > 0 ? true : false;
                        grvLopMonhoc.MasterTableView.Columns.FindByUniqueName("btnDelete").Display = pq.DELETE > 0 ? true : false;
                        //grvLopHocvien.MasterTableView.Columns.FindByUniqueName("btnEdit").Display = pq.EDIT > 0 ? true : false;
                    }
                }





                grvLopMonhoc.Culture = new CultureInfo("vi-VN");
                grvLopMonhoc.Rebind();
                              

                var listLOPHOC = (from lh in db.LST_LOPHOCs
                                  where lh.TRANGTHAI.Equals("1")
                                  select lh).ToList().OrderBy(a=>a.TENLH);

                ddlLOPHOC.DataSource = listLOPHOC;
                ddlLOPHOC.DataTextField = "TENLH";
                ddlLOPHOC.DataValueField = "MALH";
                ddlLOPHOC.DataBind();
                fillgrvLopMonhoc();
                grvLopMonhoc.DataBind();

            }
        }

        
        protected void RadSearchBox1_Search(object sender, Telerik.Web.UI.SearchBoxEventArgs e)
        {
            {
                BVVDDataContext db = new BVVDDataContext();

                RadSearchBox searchBox = (RadSearchBox)sender;
                RadListBox rad = searchBox.NamingContainer.FindControl("lboxMONHOC") as RadListBox;

                if (e.DataItem != null)
                {
                    rad.DataSource = (from mh in db.LST_MONHOCs
                                      where (mh.MAMH).Contains(((Dictionary<string, object>)e.DataItem)["MAMH"].ToString())
                                      select new
                                      {
                                          NAME = mh.TENMH + " | " + mh.MAMH,
                                          MAMH = mh.MAMH,
                                          TENMH = mh.TENMH

                                      }).ToList().OrderBy(a=>a.TENMH);


                }
                else
                {
                    (searchBox.NamingContainer.FindControl("lblTEXT") as Label).Text = e.Text;
                    rad.DataSource = (from mh in db.LST_MONHOCs
                                      where mh.MAMH.Contains(e.Text)
                                      || mh.TENMH.Contains(e.Text)
                                      select new
                                      {
                                          NAME = mh.TENMH + " | " + mh.MAMH,
                                          MAMH = mh.MAMH,
                                          TENMH = mh.TENMH

                                      }).ToList().OrderBy(a=>a.TENMH);
                }

                rad.DataBind();

            }
        }

        protected void lboxMONHOC_Transferring(object sender, Telerik.Web.UI.RadListBoxTransferringEventArgs e)
        {
            e.Cancel = true;
            if (e.DestinationListBox.Items.Contains(e.SourceListBox.SelectedItem))
            {
                e.Cancel = true;

            }
        }

        private bool checkMHExistInClass(F_LOP_MONHOC obj)
        {
            BVVDDataContext db = new BVVDDataContext();

            bool check = (from mh in db.F_LOP_MONHOCs
                          where mh.MAMH.Equals(obj.MAMH)
                          && mh.MALH.Equals(obj.MALH)
                          select mh).ToList().Count > 0;

            return !check;

        }

        protected void LinqDataSource1_Selecting(object sender, LinqDataSourceSelectEventArgs e)
        {
            BVVDDataContext db = new BVVDDataContext();
            
            var list = (from mh in db.LST_MONHOCs
                        where mh.TRANGTHAI.Equals("1")
                        select new
                        {
                            NAME = mh.MAMH + " " + mh.TENMH,
                            MAMH = mh.MAMH,
                            TENMH = mh.TENMH
                        }).ToList().OrderBy(a=>a.TENMH);
            e.Result = list;
            
        }

        protected void ddlLOPHOC_SelectedIndexChanged(object sender, Telerik.Web.UI.DropDownListEventArgs e)
        {
            fillgrvLopMonhoc();
            grvLopMonhoc.DataBind();
        }

        protected void grvLopMonhoc_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            fillgrvLopMonhoc();
        }

        protected void grvLopMonhoc_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
        {
            if (e.Item is GridEditFormInsertItem || e.Item is GridDataInsertItem)
            {

                BVVDDataContext db = new BVVDDataContext();
                //var list = (from mh in db.LST_MONHOCs
                //            where mh.TRANGTHAI.Equals("1")
                //            select new
                //            {
                //                NAME = mh.TENMH + " | " + mh.MAMH,
                //                MAMH = mh.MAMH,
                //                TENMH = mh.TENMH
                //            }).ToList().OrderBy(a=>a.TENMH);

                var list = (from mh in db.LST_MONHOCs
                            where mh.TRANGTHAI.Equals("1")
                            join lm in db.F_LOP_MONHOCs on new { MAMH = mh.MAMH, MALH = ddlLOPHOC.SelectedValue } equals new { MAMH = lm.MAMH, MALH = lm.MALH } into temp1
                            from tmp1 in temp1.DefaultIfEmpty()
                            select new
                            {
                                NAME = mh.MAMH + " " + mh.TENMH,
                                MAMH = mh.MAMH,
                                TENMH = mh.TENMH,
                                STATUS = tmp1.TRANGTHAI
                            }).ToList().OrderBy(a => a.TENMH).Where(a => String.IsNullOrEmpty(a.STATUS));

                GridEditFormInsertItem insertedItem = (GridEditFormInsertItem)e.Item;
                RadListBox lboxMONHOC = insertedItem.FindControl("lboxMONHOC") as RadListBox;
                Label lblMH = insertedItem.FindControl("lblMAMH") as Label;
                LinkButton btnUpdate = insertedItem.FindControl("btnUpdate") as LinkButton;
                lboxMONHOC.Visible = true;



                if (ddlLOPHOC.SelectedIndex >= 0)
                {
                    lblMH.Text = "Danh sách môn học hiện tại ở lớp " + ddlLOPHOC.SelectedText;
                    lboxMONHOC.DataSource = list;
                    lboxMONHOC.DataTextField = "NAME";
                    lboxMONHOC.DataValueField = "MAMH";
                    lboxMONHOC.DataBind();







                    RadListBox lboxTOLOP = insertedItem.FindControl("lboxTOLOP") as RadListBox;
                    var target = (from mh in db.LST_MONHOCs
                                  join lp in db.F_LOP_MONHOCs on mh.MAMH equals lp.MAMH
                                  where lp.MALH.Equals(ddlLOPHOC.SelectedValue)
                                  select new
                                  {
                                      NAME = mh.TENMH + " | " + mh.MAMH,
                                      MAMH = mh.MAMH,
                                      TENMH = mh.TENMH

                                  }).ToList().OrderBy(a=>a.TENMH);
                    lboxTOLOP.DataSource = target;
                    lboxTOLOP.DataTextField = "NAME";
                    lboxTOLOP.DataValueField = "MAMH";
                    lboxTOLOP.DataBind();
                }
                else
                {
                    lblMH.Text = "<a href='/ql-hoc-tap/frmLopMonhoc.aspx'>Quay lại để chọn lớp học</a>";
                    lboxMONHOC.Visible = false;
                    btnUpdate.Enabled = false;

                }





            }
        }

        

        protected void grvLopMonhoc_InsertCommand(object sender, GridCommandEventArgs e)
        {
            BVVDDataContext db = new BVVDDataContext();
            GridEditFormInsertItem insertedItem = (GridEditFormInsertItem)e.Item;
            RadListBox lboxTOLOP = insertedItem.FindControl("lboxTOLOP") as RadListBox;
            
            List<F_LOP_MONHOC> listInsert = new List<F_LOP_MONHOC>();

            if (lboxTOLOP.Items.Count > 0)
            {

                foreach (RadListBoxItem item in lboxTOLOP.Items)
                {
                    if (!item.Value.Equals("1"))
                    {
                        
                        F_LOP_MONHOC fmh = new F_LOP_MONHOC
                        {
                            MALH = ddlLOPHOC.SelectedValue,
                            MAMH = item.Value,
                            TRANGTHAI = "1"
                            
                        };
                        if (checkMHExistInClass(fmh))
                        {
                            listInsert.Add(fmh);
                        }
                    }
                }
            }
            db.F_LOP_MONHOCs.InsertAllOnSubmit(listInsert);
            try
            {
                db.SubmitChanges();
                rnAlert.Text = listInsert.Count > 0 ? "Thêm mới <font color='red'> " + listInsert.Count + "</font> môn học vào lớp <font color='red'> " + ddlLOPHOC.SelectedText + "</font> thành công " : "Không có môn học nào được thêm vào lớp <font color='red'> " + ddlLOPHOC.SelectedText + "</font>";
            }
            catch (Exception ex)
            {
                rnAlert.Text = "Có lỗi xảy ra \n <br /> Nguyên nhân : " + ex.Message;

            }


            rnAlert.Show();
        }

        protected void grvLopMonhoc_DeleteCommand(object sender, GridCommandEventArgs e)
        {
            GridDataItem item = (GridDataItem)e.Item;
            string recid = item.OwnerTableView.DataKeyValues[item.ItemIndex]["RECID"].ToString();
            BVVDDataContext db = new BVVDDataContext();
            F_LOP_MONHOC record = (from lm in db.F_LOP_MONHOCs
                                   where lm.RECID.ToString().Equals(recid)
                                   select lm).SingleOrDefault();
            string mamh = record.LST_MONHOC.TENMH;
            string malh = record.LST_LOPHOC.TENLH;
            db.F_LOP_MONHOCs.DeleteOnSubmit(record);
            try
            {
                db.SubmitChanges();
                rnAlert.Text = "Xóa thành công môn học <font color='red'> " + mamh + "</font> khỏi danh sách các môn học của lớp " + malh + "</font>";
            }
            catch (Exception ex)
            {
                rnAlert.Text = "Có lỗi xảy ra. \n <br /> Nguyên nhân : " + ex.Message;
            }

            rnAlert.Show();
        }

        private void fillgrvLopMonhoc() {
            BVVDDataContext db = new BVVDDataContext();
            var list = (from lmh in db.F_LOP_MONHOCs
                        where lmh.MALH.Equals(ddlLOPHOC.SelectedValue)
                        select new
                        {
                            RECID = lmh.RECID,
                            MALH = lmh.MALH,
                            TENLH = lmh.LST_LOPHOC.TENLH,
                            MAMH = lmh.MAMH,
                            TENMH = lmh.LST_MONHOC.TENMH,
                            TRANGTHAI = lmh.TRANGTHAI,
                            GHICHU = lmh.GHICHU

                        }).ToList().OrderBy(a=>a.TENLH);
            grvLopMonhoc.DataSource = list;
        
        }
    }
}